package com.javaking.clanteam.studentutils.courses;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.javaking.clanteam.calendar.provider.CalendarContract.Events;
import com.javaking.clanteam.studentutils.R;
import com.javaking.clanteam.studentutils.sql.CourseHelper;
import com.javaking.clanteam.studentutils.utils.DatePair;
import com.javaking.clanteam.studentutils.utils.EditableListFragment;
import com.javaking.clanteam.studentutils.utils.OnItemsChangedListener;

public class EditCourseFragment extends SherlockFragment implements
					OnItemsChangedListener<DatePair>{
	
	CourseData mCourseData;
	
	EditableListFragment<DatePair> mTimesFrag;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		try {
			Bundle args = getArguments();
			mCourseData = args.getParcelable("course");
			if (mCourseData==null) 
				throw new NullPointerException();
		} catch (NullPointerException e) {
			throw new IllegalArgumentException("You must provide a course for this" +
					" fragment to edit.");
		}
		
		setHasOptionsMenu(true);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_addcourse, container,false);
		Button button = (Button)v.findViewById(R.id.addCourseButton);
		button.setText(R.string.edit);
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View clicked) {
				View v = getView();
				CourseData.Builder builder = new CourseData.Builder();
				String courseName = ((EditText)v.findViewById(R.id.courseNameEdit)).getText().toString();
				builder.setCourseTitle(courseName);
				String teacher = ((EditText)v.findViewById(R.id.teacherEdit)).getText().toString();
				builder.setTeacher(teacher);
				String room = ((EditText)v.findViewById(R.id.roomEdit)).getText().toString();
				builder.setRoom(room);
				
				for (DatePair pair : mTimesFrag.getItems()) {
					builder.addTime(pair);

					SharedPreferences prefs = PreferenceManager
							.getDefaultSharedPreferences(getActivity());
					
					ContentValues cv = new ContentValues();
					cv.put(Events.CALENDAR_ID, prefs
								.getString("useCalendar", "1"));
					cv.put(Events.TITLE, courseName);
					cv.put(Events.EVENT_LOCATION, "Room: "+room);
					cv.put(Events.START_TIME, pair.getStartDate().getTime());
					cv.put(Events.END_TIME, pair.getEndDate().getTime());
					cv.put(Events.EVENT_TIMEZONE, Calendar.getInstance().getTimeZone().getDisplayName());
					
					Events.RRuleBuilder rbuilder = new Events.RRuleBuilder();
					rbuilder.setUntil(new Date(prefs.getLong("endDat", System.currentTimeMillis())));
					rbuilder.setFreq(Events.RRuleBuilder.Frequencies.WEEKLY);
					cv.put(Events.RRULE, rbuilder.buildRRule());
					
					getActivity().getContentResolver().insert(Events.CONTENT_URI, cv);
				}
				
				CourseHelper helper = new CourseHelper(getActivity());
				helper.updateCourse(mCourseData, builder.build());
				
				getFragmentManager().popBackStack();
			}
		});
		
		((EditText)v.findViewById(R.id.courseNameEdit)).setText(mCourseData.getCourseTitle());
		((EditText)v.findViewById(R.id.teacherEdit)).setText(mCourseData.getTeacher());
		((EditText)v.findViewById(R.id.roomEdit)).setText(mCourseData.getRoom());
		
		return v;
	}
	
	@SuppressLint("NewApi")
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		mTimesFrag = EditableListFragment.addToFrame(getActivity(), mCourseData.getTimes(), true, NewTimeDialog.class);
		
		getSherlockActivity().getSupportActionBar().setTitle
			(String.format("Edit %s", mCourseData.getCourseTitle()));
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.fragment_coursemanagement, menu);
	}

	@Override
	public void onItemsAdded(List<DatePair> items) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onItemRemoved(DatePair item) {
		// TODO Auto-generated method stub
		
	}

}
